const moment = require('moment')
const md5 = require('md5')
const jwt = require('jwt-simple')
const {Formidable} = require('formidable')
const fs = require('fs')
const path = require('path')
const KEY = 'for(let i=0;i<10000;i++){console.log("iloveyou")}'
module.exports = {
    getNowTime:()=>{
        return moment().format('YYYY-MM-DD HH:mm:ss')
    },
    md5:(password)=>{
        return md5(password + KEY)
    },
    // 加密
    encode:(payload,exp=60*60*24)=>{
        payload.exp = Date.now()/1000 + exp
        return jwt.encode(payload,KEY)
    },
    // 解密
    decode:token=>{
        return new Promise((resolve,reject)=>{
            try{
                let payload = jwt.decode(token,KEY)
                resolve(payload)
            }catch(e){
                reject(e.message)
            }
        })
    },
    upload:(request,attr)=>{
        const form = new Formidable({
            uploadDir:path.resolve(__dirname,'../public/upload'),
            // 是否保留扩展名
            keepExtensions:true
        })
        return new Promise((resolve,reject)=>{
            form.parse(request,async (err,fields,files)=>{
                if(err){
                    console.log('err');
                    reject(err)
                }
                let file = files[attr]
                console.log(file);
                if(file.size === 0){
                    // 文件大小为0时，说明没有上传文件，删除upload中的空文件
                    fs.unlinkSync(file.filepath)
                }else{
                    fields[attr] = file.newFilename
        
                }
                resolve(fields)
            })
        })}
        
    
}